import os
import re

import joblib
import requests
import uvicorn
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
count_path="count.joblib"
app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"],
                   allow_headers=["*"])
app.state = {'login_user_key': ''}

@app.get("/get_img")
def read_item(req: Request):
    res = requests.post('https://sso.e.qq.com/login/wx_applet/qr_code').json()
    qr_code = f"data:image/jpeg;base64,{res['data']['qr_code']}"
    req.app.state['login_user_key'] = res['data']['login_user_key']
    print(f"已保存login_user_key:{req.app.state['login_user_key']}")
    return qr_code
@app.get("/add_count")
def add_count(req: Request):
    if os.path.exists(count_path):
        use_count=joblib.load(count_path)+1
    else:
        use_count=1
    joblib.dump(use_count, count_path)
    return ""

@app.get("/get_count")
def get_count(req: Request):
    if os.path.exists(count_path):
        return  joblib.load(count_path)
    else:
        return 0

def get_acrf_token(s) -> int:
    hash_val = 5381
    for ch in s:
        hash_val += (hash_val << 5) + ord(ch)
    return hash_val & 0x7fffffff


@app.get("/check")
def check(req: Request):
    res = requests.post('https://sso.e.qq.com/login/wx_applet/confirm',
                        json={"login_user_key": req.app.state['login_user_key']}).json()
    if res['code'] == 0:
        ad_ticket = res['data']['ad_ticket']
        session_id = res['data']['session_id']
        ticket_res = requests.get(f'https://ad.qq.com/ap/sso/check_ticket?sso_ticket={ad_ticket}')
        if ticket_res.json()['code'] == 0:
            cookies_str = ticket_res.headers.get('Set-Cookie')
            gdt_token = re.findall(r'gdt_token=([^;,]+)', cookies_str)
            gdt_protect = re.findall(r'gdt_protect=([^;,]+)', cookies_str)
            if len(gdt_token) > 0:
                gdt_token = gdt_token[0]
            if len(gdt_protect) > 0:
                gdt_protect = gdt_protect[0]
            gtk = get_acrf_token(gdt_protect)
            get_user_res = requests.get(f'https://e.qq.com/agp/auth/get_user?g_tk={gtk}',
                                        headers={
                                            'Cookie': f'gdt_token={gdt_token}; gdt_protect={gdt_protect}'}).json()
            if get_user_res['code'] != 0:
                return {'code': 2, "data": None}
            get_user_res = get_user_res['data']
            bm_id = get_user_res['bm_id']
            trace_user_id = get_user_res['user_id']
            trace_agency_id = get_user_res['sale_agency_uid']
            trace_company_id = get_user_res['company_id']
            agency_uid = get_user_res['agency_list'][0]['agency_uid']
            return {'code': 0,
                    'data': {"gdt_token": gdt_token,
                             'gdt_protect': gdt_protect,
                             "gtk": gtk,
                             'session_id': session_id,
                             'bm_id': bm_id,
                             'trace_user_id': trace_user_id,
                             'trace_agency_id': trace_agency_id,
                             'trace_company_id': trace_company_id,
                             'agency_uid': agency_uid}
                    }
    return {'code': 1, 'data': None}
uvicorn.run(app, host="0.0.0.0", port=9090)
